<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1400">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="提成" prop="tc">
            <el-input v-model="formData.tc" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报价单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
              clearable
              filterable
              placeholder="请选择客户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单日期" prop="orderTime">
            <el-date-picker
              v-model="formData.orderTime"
              type="date"
              value-format="x"
              placeholder="请选择"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报价开始时间" prop="bjStartTime">
            <el-date-picker
              v-model="formData.bjStartTime"
              type="date"
              value-format="x"
              placeholder="请选择"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" prop="preparer">
            <el-select
              v-model="formData.preparer"
              clearable
              filterable
              placeholder="请选择"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售类型" prop="salesType">
            <el-radio-group v-model="salesType">
              <el-radio value="1">产品</el-radio>
              <el-radio value="2"> 物料 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报价人" prop="quoter">
            <el-select
              v-model="formData.quoter"
              clearable
              filterable
              placeholder="请选择"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附加说明" prop="additionalNotes">
            <el-input v-model="formData.additionalNotes" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报价结束时间" prop="bjEndTime">
            <el-date-picker
              v-model="formData.bjEndTime"
              type="date"
              value-format="x"
              placeholder="请选择"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="摘要" prop="abstract">
            <el-input v-model="formData.abstract" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="含税金额" prop="amountIncludingTax">
            <el-input v-model="formData.amountIncludingTax" placeholder="请选择" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="不含税金额" prop="amountExcludingTax">
            <el-input v-model="formData.fee" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目" prop="project">
            <el-input v-model="formData.project" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目阶段" prop="projectPhase">
            <el-select
              v-model="formData.projectPhase"
              clearable
              filterable
              placeholder="请选择"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户订单编号" prop="cusOrderCode">
            <el-input v-model="formData.cusOrderCode" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件" prop="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设计图" prop="planImg">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="收获地址" name="item">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="consignee" label="收货人" />
            <el-table-column prop="contact" label="联系方式" />
            <el-table-column prop="address" label="收货地址" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="联系信息" name="item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系人姓名" prop="contactName">
                <el-input v-model="formData.contactName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="sex">
                <el-input v-model="formData.sex" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  type="date"
                  value-format="x"
                  class="!w-1/1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职务" prop="office">
                <el-input v-model="formData.office" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="mobilePhone">
                <el-input v-model="formData.mobilePhone" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="formData.email" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="QQ" prop="qq">
                <el-input v-model="formData.qq" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="固定电话" prop="telephone">
                <el-input v-model="formData.telephone" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="微信" prop="wechat">
                <el-input v-model="formData.wechat" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯" prop="hometown">
                <el-input v-model="formData.hometown" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="产品列表" name="item">
          <ProductList
            ref="itemFormRef"
            :items="formData.items"
            :disabled="disabled"
            @success="handleProductList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import * as UserApi from '@/api/system/user'
import ProductList from './components/productList.vue'
/** ERP 销售订单表单 */
defineOptions({ name: 'SaleOrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const tableData = ref([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  customerId: undefined,
  accountId: undefined,
  saleUserId: undefined,
  orderTime: undefined,
  remark: undefined,
  fileUrl: '',
  discountPercent: 0,
  discountPrice: 0,
  totalPrice: 0,
  depositPrice: 0,
  items: [],
  no: undefined // 订单单号，后端返回
})
const salesType = ref('1')
const formRules = reactive({
  no: [{ required: true, message: '请选择', trigger: 'blur' }],
  customerId: [{ required: true, message: '请选择', trigger: 'blur' }],
  orderTime: [{ required: true, message: '请选择', trigger: 'blur' }],
  bjStartTime: [{ required: true, message: '请选择', trigger: 'blur' }],
  bjEndTime: [{ required: true, message: '请选择', trigger: 'blur' }],
  salesType: [{ required: true, message: '请选择', trigger: 'blur' }],
  preparer: [{ required: true, message: '请选择', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表
const accountList = ref<AccountVO[]>([]) // 账户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalPrice = val.items.reduce((prev, curr) => prev + curr.totalPrice, 0)
    const discountPrice =
      val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
    formData.value.discountPrice = discountPrice
    formData.value.totalPrice = totalPrice - discountPrice
  },
  { deep: true }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + '报价单'
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      // formData.value = await SaleOrderApi.getSaleOrder(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载客户列表
  // customerList.value = await CustomerApi.getCustomerSimpleList()
  // 加载用户列表
  // userList.value = await UserApi.getSimpleUserList()
  // 加载账户列表
  // accountList.value = await AccountApi.getAccountSimpleList()
  const defaultAccount = accountList.value.find((item) => item.defaultStatus)
  if (defaultAccount) {
    formData.value.accountId = defaultAccount.id
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleOrderVO
    if (formType.value === 'create') {
      // await SaleOrderApi.createSaleOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      // await SaleOrderApi.updateSaleOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    accountId: undefined,
    saleUserId: undefined,
    orderTime: undefined,
    remark: undefined,
    fileUrl: undefined,
    discountPercent: 0,
    discountPrice: 0,
    totalPrice: 0,
    depositPrice: 0,
    items: []
  }
  formRef.value?.resetFields()
}
</script>
